package com.zheng.redpacket.server.serivce.Impl;

import com.zheng.redpacket.mdg.mapper.MqOrderMapper;
import com.zheng.redpacket.mdg.mapper.UserOrderMapper;
import com.zheng.redpacket.mdg.model.MqOrder;
import com.zheng.redpacket.mdg.model.UserOrder;
import com.zheng.redpacket.server.dto.OrderDto;
import com.zheng.redpacket.server.serivce.UserOrderService;
import com.zheng.redpacket.server.utils.publisher.OrderPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class UserOrderServiceImpl implements UserOrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserOrderServiceImpl.class);

    @Autowired
    private UserOrderMapper orderMapper;
    @Autowired
    private MqOrderMapper mqOrderMapper;
    @Autowired
    private OrderPublisher publisher;

    @Override
    public void pushUserOrder(OrderDto dto) {
        UserOrder order = new UserOrder();
        BeanUtils.copyProperties(dto, order);
        order.setStatus(0);
        order.setCreateTime(new Date());
        orderMapper.insertSelective(order);
        LOGGER.info("用户下单成功，下单时间{}", order.getCreateTime());
        Integer id = order.getId();
        publisher.sendMsg(id);
    }

    @Override
    public void updateUserOrderRecord(UserOrder order) {
        try {
            if (order != null) {
                order.setIsActive(0);
                order.setUpdateTime(new Date());
                orderMapper.updateByPrimaryKeySelective(order);
                MqOrder mqOrder = new MqOrder();
                mqOrder.setBusinessTime(order.getUpdateTime());
                mqOrder.setMemo(order.getId() + ":订单失效");
                mqOrder.setOrderId(order.getId());
                mqOrderMapper.insertSelective(mqOrder);
            }
        } catch (Exception e) {
            LOGGER.error("更新用户下单记录状态时发生异常：", e.fillInStackTrace());
        }
    }
}
